# -*- encoding:utf-8 -*-
"""
transfer the 19bu.txt to format of dic
"""
import os,sys
from pinyincommon import splitpinyin
from pinyincommon import YunmuPinyinException
from pinyin import getpinyincode

class Yun13NotExistException(Exception):pass

def transfer19bu():
    """
    transfer 19bu.txt to format of dic in order to create module
    @see get19budic
    @return output to file 19butmp
    """
    f = open("19butmp","w")
    print>>f,"bu19dic = {"
    budic = get19budic()
    for k in budic.keys():
        print>>f,"u'"+k.encode("utf-8")+"':"+str(budic[k])+','
    print>>f,"}"

def get19budic():
    """
    startswith * the class lable
    startswith # the comment
    other non-empty line,the content
    return the 19budic
    """
    f = open("19bu.txt")
    lines = f.readlines()
    f.close()

    dic = {}
    curlabel = ""
    for line in lines:
        if line.endswith("\r\n"):
            line = line[0:len(line)-2]
        if line.startswith("#"):
            continue
        if line.startswith("*"):
            curlabel = line[1:len(line)]
            continue
        if line != "":
            words = line.decode("utf-8")
            for word in words:
                if not dic.has_key(word):
                    dic[word] = []
                    #raise Exception("duplicate")
                dic[word].append(curlabel)
    return dic



def transfer13yun():
    """
    transfer the word in the inverseGBKPYxls.txt into the yun
    output to the 13yuntmp file
    """
    f = open("inverseGBKPYxls.txt")
    lines = f.readlines()
    f.close()
    
    f = open("yun13tmp","w")
    print>>f,"yun13dic = {"
    for line in lines:
        if line.endswith("\r\n"):
            line = line[0:len(line)-2]
        if line.endswith("\r"):
            line = line[0:len(line)-1]
        if line.endswith("\n"):
            line = line[0:len(line)-1]
        words = line.split(",")
        if words[0] == "":
            #raise Exception(str(words))
            continue
        tmpstr = "u'"+words[0]+"':["
        tmpdic = []
        for i in range(1,len(words)):
            tmpcode = pinyin213yun(words[i])
            if tmpcode == -1:
                print pinyin+" yunerror: "+words[i]
            if tmpdic.count(tmpcode) == 0:
                tmpdic.append(tmpcode)
                tmpstr += str(tmpcode)+","
        tmpstr = tmpstr[0:len(tmpstr)-1]
        tmpstr += "],"
        print>>f,tmpstr
    print>>f,"}"
    f.close()


yunmu2code={
'eng':13,'ing':13,'ueng':13,'ong':13,'iong':13,
'ang':12,'iang':12,'uang':12,
'i':4,'er':4,'v':4,
'ei':7,'uei':7,
'ou':9,'iou':9,
'e':2,'o':2,'uo':2,
'en':11,'in':11,'uen':11,'vn':11,'un':11,
'an':10,'ian':10,'uan':10,'van':10,
'a':1,'ia':1,'ua':1,
'ie':3,'ve':3,
'ai':6,'uai':6,
'u':5,
'ao':8,'iao':8,
}

def pinyin213yun(pinyin):
    """
    input a pinyin and output a yun code
    if yunmu is e and there is no shengmu,is the yun 3
    if the yunmu don not have the corresponding key,return -1
    """
    global yunmu2code
    try:
        dic = splitpinyin(pinyin)
    except YunmuPinyinException:
        return -1
    except:
        return -1
    if dic['shengmu'] == "" and dic['yunmu'] == 'e':
        return 3
    if yunmu2code.has_key(dic['yunmu']):
        return yunmu2code[dic['yunmu']]
    else:
        raise Yun13NotExistException(pinyin)


def transferpinyin():
    """
    read from inverseGBKPYxls.txt to get all possible value or just read from the excel?
    delete the excel for is not convinent to process automatically
    """
    f = open("inverseGBKPYxls.txt")
    lines = f.readlines()
    f.close()
    
    f = open("pinyintmp","w")
    print>>f,"pinyindic = {"
    for line in lines:
        if line.endswith("\r\n"):
            line = line[0:len(line)-2]
        if line.endswith("\n"):
            line = line[0:len(line)-1]
        if line.endswith("\r"):
            line = line[0:len(line)-1]
        words = line.split(",")
        if words[0] == "":
            #raise Exception(str(words))
            continue
        tmpstr = "u'"+words[0]+"':["
        for i in range(1,len(words)):
            tmpstr += "'"+words[i] + "',"
        tmpstr = tmpstr[0:len(tmpstr)-1]
        tmpstr += "],"
        print>>f,tmpstr
    print>>f,"}"
    f.close()

if __name__ == "__main__":
    #transfer19bu()
    #transferpinyin()
    transfer13yun()
